package config

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gopkg.in/yaml.v3"
	"log"
	"user_service/global"
)

var Configs *Config

type Config struct {
	Server  Server       `yaml:"server" mapstructure:"server"`
	DB      Database     `yaml:"database" mapstructure:"database"`
	Redis   Redis        `yaml:"redis" mapstructure:"redis"`
	Consul  ConsulConfig `yaml:"consul" mapstructure:"consul"`
	JWT     JWT          `yaml:"jwt" mapstructure:"jwt"`
	Log     Log          `yaml:"log" mapstructure:"log"`
	Upload  Upload       `yaml:"upload" mapstructure:"upload"`
	Swagger Swagger      `yaml:"swagger" mapstructure:"swagger"`
	Ignored Ignored      `yaml:"ignored" mapstructure:"ignored"`
}

func init() {
	// 获取到viper后读取文件配置，用于后续连接consul
	envConfig := initViper()
	var client *api.Client
	var err error

	// 初始化consul配置对象
	cfg := api.DefaultConfig()
	cfg.Address = fmt.Sprintf("%s:%d", envConfig.Consul.Config.Host, envConfig.Consul.Config.Port)
	cfg.Token = envConfig.Consul.Config.ACLToken

	// 初始化客户端
	client, err = api.NewClient(cfg)
	global.Client = client
	if err != nil {
		log.Fatal(err)
	}

	// 读取用户服务配置
	kvPair, _, err := client.KV().Get("miaoshang_service/user.yaml", nil)
	if err != nil {
		log.Fatal(err)
	}
	if kvPair == nil {
		log.Fatal("Key not found in Consul")
	}
	var config Config
	err = yaml.Unmarshal(kvPair.Value, &config)
	if err != nil {
		log.Fatal(err)
	}
	Configs = &config
	// 全局配置中心
	Configs.Consul.Config = envConfig.Consul.Config
	// 全局注册中心
	Configs.Consul.Discovery = envConfig.Consul.Discovery

	log.Println("Config initialized successfully")
	zap.S().Info("读取配置成功")
}

// 初始化viper
func initViper() Config {
	viper.SetConfigName("env")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./../")
	if err := viper.ReadInConfig(); err != nil {
		log.Fatalf("Error reading config file: %v", err)
	}

	// 读取本地配置文件
	if err := viper.ReadInConfig(); err != nil {
		panic(fmt.Errorf("读取配置文件出错: %w", err))
	}

	// 解析本地配置文件
	var LocalConfigs Config
	if err := viper.Unmarshal(&LocalConfigs); err != nil {
		panic(fmt.Errorf("解析配置文件出错: %w", err))
	}

	// 返回本地配置
	return LocalConfigs
}
